// app.js
var httpTool = require("./utils/httpTool.js");

App({
  d: {
    imageUrlFix: 'http://fish.fzgsh.top/ecommerce/',
    hostUrl: 'https://fish.fzgsh.top/api/v1',
    // hostUrl: 'http://127.0.0.1:7001/api/v1',
    hostImg: 'http://img.ynjmzb.net',
    hostVideo: 'http://zhubaotong-file.oss-cn-beijing.aliyuncs.com',
    userId: 1,
    duserId:-1,
    token:"",
    sellerInfo:null,
    appId:"",
    debugApp:"",
    appKey:"",
    shareId:-1,
    ceshiUrl:'https://fish.fzgsh.top/api/v1',
    // ceshiUrl: 'http://127.0.0.1:7001/api/v1',
    indexCallback:null,//首页回调方法
    currType: 0,
  },
  onLaunch: function (options) {
  },
  getUserInfo:function(cb){
    var that = this
    //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs);
    if(this.globalData.userInfo){
        that.callbackIndexInit();
      typeof cb == "function" && cb(this.globalData.userInfo)
    }else{
      //调用授权接口
      that.authorizeGetUserInfo();
    }
  },
  distributorMemberRel:function(){
    var that = this;
    console.log("===rel uid:" + that.d.duserId);
    //关联绑定分销商
    that.request("DistributorService", "distributorMemberRel", {
      uid: that.d.userId,
      duid: that.d.duserId,
      shareId: that.d.shareId,
    }, function (data) {
      that.d.duserId = data.duid;
      that.d.sellerInfo = data.sellerInfo;
      that.callbackIndexInit();
    });
  },
    /**
     * 采用timeout方式，避免index未加载先执行callback，导致程序异常
     */
  callbackIndexInit:function(){
    var that = this;
    try{
      that.d.indexCallback("init");
    }catch(e){
      //调用callback失败，延迟500毫秒重试，直至调用成功
      setTimeout(function () { that.callbackIndexInit();},500);
    }
  },
  authorizeGetUserInfo:function(){
    // wx.getSetting({
    //   success(res) {
    //     if (!res.authSetting['scope.userInfo']) {
    //       wx.authorize({
    //         scope: 'scope.userInfo',
    //         success() {
    //           //调用登录接口
    //           doLogin();
    //         },
    //         fail: function(){

    //         }
    //       })
    //     } else if (res.authSetting['scope.userInfo']){
    //       //调用登录接口
    //       doLogin();
    //     }
    //   },
    //   complete:function(res){
    //     wx.showToast({
    //       title: res,
    //       duration: 2000
    //     });
    //   }
    // })
    this.doLogin();
  },

  doLogin:function(){
    var self = this;
    wx.login({
      success: function (res) {
        var code = res.code;
        //get wx user simple info
       
        self.getUserInfoAuth(code);
      }
    });
  },

  getUserInfoAuth: function (code){
    var self = this;
     wx.getUserInfo({
          success: function (res) {
            //可以在这边获取userInfo、rawData、signature、encryptedData和iv
            self.globalData.userInfo = res.userInfo;
            self.globalData.rawData = res.rawData;
            self.globalData.signature = res.signature;
            self.globalData.encryptedData = res.encryptedData;
            self.globalData.iv = res.iv;
            self.getUserSessionKey(code);
          }
        });
  },

  getUserSessionKey:function(code){
    //用户的订单状态
    var that = this;

    //此段为了测试使用
    var timestamp = Date.parse(new Date());
    that.globalData.userInfo['openid'] = timestamp;
    // that.wxRegister(); 
    //关联绑定分销商
    that.request("WxmanageService", "getOpenIdAndSessionKey", {
      credentialCode: code
    }, function (data,result) {
      that.d.token = result.token;
      that.globalData.others['sessionKey'] = data.session_key;
      that.globalData.userInfo['openid'] = data.openid;
      that.globalData.others['unionid'] = data.unionid;
      that.wxRegister(); 
    });
    // wx.request({
    //   url: that.d.ceshiUrl + '/WxmanageService/getOpenIdAndSessionKey',
    //   method:'post',
    //   data: {
    //     credentialCode: code
    //   },
    //   header: {
    //     'Content-Type':  'application/json'
    //   },
    //   success: function (res) {
    //     //--init data        
    //     var result = res.result;
    //     if (result==1){
    //       wx.showToast({
    //         title: res.message,
    //         duration: 2000
    //       });
    //       return false;
    //     }
    //     that.globalData.others['sessionKey'] = res.session_key;
    //     that.globalData.others['openid'] = res.openid;
    //     that.globalData.others['unionid'] = res.unionid;
    //     //that.onLoginUser();
    //   },
    //   fail:function(e){
    //     wx.showToast({
    //       title: '网络异常！err:getsessionkeys',
    //       duration: 2000
    //     });
    //   },
    // });
  },

  wxRegister: function () {
    var that = this;
    that.request("RegisterService", "wxRegister", {
      nickName: that.globalData.userInfo['nickName'],
      avatarUrl: that.globalData.userInfo['avatarUrl'],
      gender: that.globalData.userInfo['gender'],
      openid: that.globalData.userInfo['openid']
    }, function (data) {
      var userId = data['userId'];
      var userType = data['userType'];
      that.d.userId = userId;
      that.d.userType = userType;
      that.globalData.userInfo['userId'] = userId;
      that.globalData.userInfo['userType'] = userType;
      that.distributorMemberRel();
    });
  },

  onLoginUser:function(){
    var that = this;
    var user = that.globalData.userInfo;
    wx.request({
      url: that.d.ceshiUrl + '/Api/Login/authlogin',
      method:'post',
      data: {
        SessionId: user.sessionId,
        gender:user.gender,
        NickName: user.nickName,
        HeadUrl: user.avatarUrl,
        openid:user.openid
      },
      header: {
        'Content-Type':  'application/x-www-form-urlencoded'
      },
      success: function (res) {
        //--init data        
        var data = res.data.arr;
        var status = res.data.status;
        if(status!=1){
          wx.showToast({
            title: res.data.err,
            duration: 3000
          });
          return false;
        }
        that.globalData.userInfo['id'] = data.ID;
        that.globalData.userInfo['NickName'] = data.NickName;
        that.globalData.userInfo['HeadUrl'] = data.HeadUrl;
        var userId = data.ID;
        if (!userId){
          wx.showToast({
            title: '登录失败！',
            duration: 3000
          });
          return false;
        }
        that.d.userId = userId;
      },
      fail:function(e){
        wx.showToast({
          title: '网络异常！err:authlogin',
          duration: 2000
        });
      },
    });
  },
  getOrBindTelPhone:function(returnUrl){
    var user = this.globalData.userInfo;
    if(!user.tel){
      wx.navigateTo({
        url: 'pages/binding/binding'
      });
    }
  },

 globalData:{
    userInfo:null,
    rawData:null,
    signature:null,
    encryptedData:null,
    iv:null,
    others:{}
  },

  onPullDownRefresh: function (){
    wx.stopPullDownRefresh();
  },
  
  request:function(serviceName, methodName, options, successCallback, failCallback, completeCallback){
    var that = this;
    options['g_duid'] = that.d.duserId;
    options['debug_app'] = that.d.debugApp;
    if (that.d.sellerInfo){
      options['g_sellerid'] = that.d.sellerInfo.id;
    }else{
      options['g_sellerid'] = -1;
    }
    var data= {
      serviceName: serviceName,
      methodName: methodName,
      token: that.d.token,
      source: 'WX',
      privates: options
    };
    httpTool.sentHttpRequestToServer(
      that.d.hostUrl+"/"+serviceName+"/"+methodName,
      data,
      'post',
      successCallback, failCallback, completeCallback
    );
  },
});





